import { get, post } from "@/useHttp";
import { LoginParams, LoginResult, UserInfo } from "./structs";

/** 获取当前的用户 GET /api/queryCurrentUser */
export async function queryCurrentUser(options?: { [key: string]: any }) {
  return get<{ success: boolean, data: UserInfo }>('/api/currentUser', {}, '', {}, undefined, options);
}

/** 退出登录接口 POST /api/login/outLogin */
export async function outLogin(options?: { [key: string]: any }) {
  return post<Record<string, any>>('/api/signout', {}, options);
}

/** 登录接口 POST /api/login */
export async function login(body: LoginParams): Promise<LoginResult> {
  const { success, data: code } = await post<{ success: boolean, data: string }>('/api/code', body)
  if (success === false) return { success: false } // 取 code 失败

  // 取 code 成功 → 取 accessToken
  const res = await get<LoginResult>('/api/signin', {
    code: code,
  });
  if (res.success === true) { // accessToken
    localStorage.setItem('accessToken', res.data?.accessToken || ''); // 设置 accessToken
  }
  return res
}

/**
 * 修改密码
 * 
 * @param oldPwd 旧密码
 * @param newPwd  新密码
 * @returns 
 */
export const changePwd = async (oldPwd: string, newPwd: string) => {
  const { success } = await post('/api/changepwd', { oldPassword: oldPwd, newPassword: newPwd });
  return success
}